package rmiClient;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;

import interfaces.Client_ITF;
import interfaces.Serveur_ITF;

public class Lanceur_Client {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length != 1) {
			System.err
					.println("Usage : java client <server name or address:port number>");
			System.exit(1);
		}

		Serveur_ITF server = null;

		try {
			server = (Serveur_ITF) Naming
					.lookup("rmi://" + args[0] + "/server");
		} catch (MalformedURLException e) {
			System.err
					.println("The server name/address:port is malformed\nsomething like turing.u-strasbg.fr:1099 or 130.79.7.1:1099 is expected");
			System.exit(2);
		} catch (RemoteException e) {
			System.err
					.println("The server cannot be reach or an error occurs on the server");
			System.exit(3);
		} catch (NotBoundException e) {
			System.err
					.println("No server object has been binded on the server");
			System.exit(4);
		}

		Client_IMPL c = null;
		Client_IMPL c1 = null;
		try {
			c = new Client_IMPL(server, 1, 1);
			c1 = new Client_IMPL(server, 2, 2);
		} catch (RemoteException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}

		try {
			server.addClient((Client_ITF) c);
		} catch (RemoteException e) {
			System.err
					.println("Due to an error on the server the client cannot be registred");
			System.exit(5);
		}

		try {
			c.neighbors = server.getNeighbors(c);
			server.addClient((Client_ITF) c1);
			ArrayList<Client_ITF> newNeighbors= server.getNeighbors(c1);
			for(Client_ITF temp :newNeighbors){
				//temp.addNeighbor(c1);
			}
			c1.setNeighbors(newNeighbors);

		} catch (RemoteException e) {
			System.err
					.println("Due to an error on the server the neighbors list cannot be retrive from the server");
			System.exit(6);
		}
		
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		System.out.println("kikoo lol");

		try {
			c.display_neighbors();
			c1.display_neighbors();
		} catch (RemoteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}


		try {
			System.out.println("The client 1 has " + c.getNeighbors().size()
					+ " neighbors\nThe client 2 has "
					+ c1.getNeighbors().size() + " neighbors\n");
		} catch (RemoteException e) {
			System.err
					.println("An RMI capable method has been call on a local object this error cannot occurs");
			System.exit(7);
		}

		try {
			server.removeClient(c);
			server.removeClient(c1);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
